package Exam.view;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;


@WebServlet(name = "UploadServlet",urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        if (!ServletFileUpload.isMultipartContent(request)){
            System.out.println("不支持");
            return;
        }

        FileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(factory);

        String path=getServletContext().getRealPath("./")+ File.separator+"upload";
        File fileDir=new File(path);

        if (!fileDir.exists()){
            fileDir.mkdir();
        }

        try {
            List<FileItem> fileItems=upload.parseRequest(request);
            if(fileItems!=null){
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()){
                        continue;
                    }
                    String fileName=fileItem.getName();
                    String filePath=path+File.separator+fileName;
                    File file=new File(filePath);
                    fileItem.write(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }
}